(function () {
    'use strict';

    /**
     * @ngdoc function
     * @name webApp.controller:ApplicationCtrl
     * @description
     * # ApplicationCtrl
     * Controller of the webApp
     */
    angular.module('webApp')
        .controller('ApplicationCtrl', ["ERP_CONFIG", "$scope", "$rootScope", "$state", "USER_ROLES", "dataService", "cacheService", "$timeout", "helper", "sessionService", "$location",
            function (ERP_CONFIG, $scope, $rootScope, $state, USER_ROLES, dataService, cacheService, $timeout, helper, sessionService, $location) {
                var currentWareHouseKey = "currentWareHouse";
                //初始化
                function GetQueryString(name) {
                    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                    var r = window.location.search.substr(1).match(reg);
                    if (r != null) return unescape(r[2]); return null;
                }
                function getLocalTime(nS) {
                    return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ');
                }

                $scope.init = function () {
                    $scope.currentUser = null;
                    $scope.userRoles = USER_ROLES;
                    //初始化
                    if (!window.localStorage.lang) {
                        window.localStorage.lang = 'zh-cn';
                    }
                    //语言设定
                    $scope.cur_lang = window.localStorage.lang;
                    $scope.code = GetQueryString("code");
                    $timeout(function () {
                        if (!$rootScope.currentUser) {
                            // if($scope.code&&(!sessionService.get("token"))){
                            //       $scope.wxcodeput($scope.code);
                            //   }else{
                            // $scope.wxcodeput();
                            $rootScope.getUserInfo(true);
                            // }
                        }
                    }, 1000);
                }
                $scope.loginUpdate = function () {
                    var data = { password_old: $scope.password, password_new: $scope.password_confirm };
                    dataService.buyerUpdatePw(data).then(function (result) {
                        if (result.Msg) {
                            helper.myAlert("error：" + result.Msg);
                        } else if (result && result.user_id) {
                            $state.go("user.list");
                            $rootScope.$broadcast('event:auth-shoploginRequired');
                        }
                    });
                }
                $scope.loginAdd = function () {
                    //,phone:$scope.phone,email:$scope.email
                    var data = { user_name: $scope.user_name, password: $scope.password, password_confirm: $scope.password_confirm };
                    dataService.buyerRegister(data).then(function (result) {
                        if (result.Msg) {
                            helper.myAlert("error：" + result.Msg);
                        } else if (result && result.user_id) {
                            $state.go("main");
                            $rootScope.$broadcast('event:auth-shoploginRequired');
                        }
                    })
                }
                //*-------------------------------------------
                //** 全局侦听事件
                //-------------------------------------------*/

                $rootScope.$on('event:login-dialog-init-done', function () {
                    $timeout(function () {
                        $scope.code = GetQueryString("code");
                        dataService.getToken(function () {

                        });
                    })
                });

                $rootScope.is_weixin = function () {
                    var ua = navigator.userAgent.toLowerCase();

                    if (ua.match(/MicroMessenger/i) == "micromessenger") {
                        return true;
                    } else {
                        return false;
                    }
                }

                //*-------------------------------------------
                // ** 全局rootScope定义 start
                // -------------------------------------------*/
                $rootScope.getUserInfo = function (getCache) {
                    return dataService.userCurrentGet(getCache).then(function (user) {
                        $rootScope.currentUser = $scope.currentUser = user || null;
                        // getWareHouseList();
                        //通知加载菜单

                        $rootScope.$broadcast("event:load-menu");
                    });
                }

                //登陆后获取用户信息
                $scope.$on('event:auth-loginConfirmed', function () {
                    $rootScope.getUserInfo();
                });
                $rootScope.login = function () {
                    $rootScope.$broadcast('event:auth-shoploginRequired');
                }

                //重新登录
                $rootScope.relogin = function () {
                    $scope.currentUser = null;
                    $timeout(function () {
                        $rootScope.login();
                    }, 300)
                }

                //注销登录
                $rootScope.logout = function () {
                    dataService.logout().then(function () {
                        $scope.currentUser = null;
                        $state.go("user.list");
                        // helper.myAlert("success", null, 3, function() {
                        $timeout(function () {
                            $rootScope.login();
                        });
                        // });
                    });
                }

                //清空缓存
                $rootScope.removeAllCache = function ($event) {
                    dataService.removeDataCache();
                    // location.reload();
                    helper.myTip("success", $event.currentTarget, null, null, null, "bottom");
                }

                //是否debug状态
                $rootScope.debug = function () {
                    return ERP_CONFIG.debug ? true : false;
                }
                $rootScope.FavoritesAdd = function (goods) {
                    // goods.buyer_id=sessionService.get("currentUserInfo").user_id;
                    goods.buyer_id = cacheService.get("currentUserInfo").user_id;
                    return dataService.favoritesAdd(goods).then(function (r) {
                        return r;
                    });
                }
                $rootScope.FavoritesGet = function () {
                    return dataService.favoritesGet().then(function (r) {
                        if (r.Msg) {
                            helper.myAlert("error:" + r.Msg);
                        } else {
                            return r;
                        }
                    });
                }
                $rootScope.back = function () {
                    history.back()
                }
            }
        ]);
})();
